package org.sakai.config.interceptors;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.sakai.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 登录拦截器，操作前检查是否登录，即检查redis中是否存在对应token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("x-access-token");
        response.setContentType("application/json;charset=UTF-8");
        final String jsonResponse = "{\"success\": false, \"message\": \"%s\"}";

        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            response.getWriter().write(jsonResponse.formatted("登录过期"));
            return false;
        }

        try {
            Map<String, Object> map = UserUtils.checkToken(token);
            String uid = (String) map.get("uid");
            String redisToken = (String) redisTemplate.opsForValue().get("jwt:" + uid);

            if (redisToken == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write(jsonResponse.formatted("登录过期"));
                return false;
            }

            if (redisToken.equals(token)) {
                return true;
            }

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(jsonResponse.formatted("账号已在别处登录"));
            return false;

        } catch (ExpiredJwtException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(jsonResponse.formatted("登录凭证过期"));
            return false;
        } catch (SignatureException | MalformedJwtException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(jsonResponse.formatted("登录凭证可能被篡改，请重新登录"));
            return false;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500
            response.getWriter().write(jsonResponse.formatted("未知错误"));
            return false;
        }
    }
}
